import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';

class AudioProgressWidget extends StatelessWidget {
  final Player player;
  final ValueNotifier<Position> _position =
      ValueNotifier(Position(position: 0, buffer: 0));

  AudioProgressWidget({super.key, required this.player});

  @override
  Widget build(BuildContext context) {
    player.stream.position.listen((event) {
      _position.value =
          _position.value.copyWith(buffer: event.inMilliseconds.toDouble());
    });
    return ValueListenableBuilder(
      valueListenable: _position,
      builder: (context, position, child) => Slider(
        secondaryTrackValue: player.state.buffer.inMilliseconds.toDouble(),
        max: player.state.duration.inMilliseconds.toDouble(),
        value: _position.value.position == 0
            ? _position.value.buffer
            : _position.value.position,
        onChanged: (value) {
          _position.value = _position.value.copyWith(position: value);
        },
        onChangeEnd: (value) async {
          await player.seek(Duration(milliseconds: value.toInt()));
          _position.value =
              _position.value.copyWith(buffer: value, position: 0);
        },
      ),
    );
  }
}

class Position {
  final double position;
  final double buffer;

  Position({required this.position, required this.buffer});

  @override
  int get hashCode => position.hashCode ^ buffer.hashCode;

  @override
  bool operator ==(Object other) {
    return other is Position &&
        other.position == position &&
        other.buffer == buffer;
  }

  Position copyWith({
    double? position,
    double? buffer,
  }) {
    return Position(
      position: position ?? this.position,
      buffer: buffer ?? this.buffer,
    );
  }

  @override
  String toString() {
    return 'Position(position: $position, buffer: $buffer)';
  }
}
